import axios from 'axios'
import { useGlobalStore, GlobalStoreType } from '@/store/global'
// 初始化
const service = axios.create({
  timeout: 5000,
  baseURL: 'http://apis.imooc.com/api/'
})
const icode = '78D4FF37F4906789'
const setPiniaState = (action: (param: GlobalStoreType) => void) => {
  const globalStore = useGlobalStore()
  action(globalStore)
}
// 请求拦截器
service.interceptors.request.use(config => {
  config.params = { ...config.params, icode } // GET
  // POST
  if (config.data instanceof FormData) {
    config.data.append('icode', icode)
  } else {
    config.data = { ...config.data, icode }
  }
  setPiniaState((globalStore: GlobalStoreType) => {
    globalStore.setLoading(true)
    globalStore.setError({ status: false, message: '' })
  })
  return config
})
// 响应拦截器
service.interceptors.response.use(
  config => {
    setPiniaState((globalStore: GlobalStoreType) => {
      setTimeout(() => {
        globalStore.loading = false
      }, 600)
    })
    return config
  },
  e => {
    setPiniaState((globalStore: GlobalStoreType) => {
      const { error } = e.response.data
      globalStore.error = { status: true, message: error }
      globalStore.loading = false
    })
    return Promise.reject(e.response.data)
  }
)
export default service
